#include "utils.h"

////////////////////全局函数//////////////////////////

/**
 * @author: 王占坤
 * @description: 显示图片
 * @param: string name 显示窗口名称
 * @param: picture 需要显示的图片
 * @param: time 显示时间，单位ms
 * @return: void
 * @throw: 
 */
void showPicture(string window_name, const cv::Mat& picture, int time)
{
    cv::namedWindow(window_name, CV_WINDOW_NORMAL);
    cv::imshow(window_name, picture);
    cv::waitKey(time);
}



void GetErrorString(GX_STATUS error_status)
{
    char *error_info = NULL;
    size_t size = 0;
    GX_STATUS status = GX_STATUS_SUCCESS;

    // 获取错误描述信息长度
    status = GXGetLastError(&error_status, NULL, &size);
    if (status != GX_STATUS_SUCCESS)
    {
        cout << "<GXGetLastError call fail>" << endl;
        return;
    }

    error_info = new char[size];
    if (error_info == NULL)
    {
        printf("<Failed to allocate memory>\n");
        return;
    }

    // 获取错误信息描述
    status = GXGetLastError(&error_status, error_info, &size);
    if (status != GX_STATUS_SUCCESS)
    {
         cout << "<GXGetLastError call fail>" << endl;
        return;
    }
    else
    {
        printf("%s\n", (char *)error_info);
    }

    // 释放资源
    if (error_info != NULL)
    {
        delete[] error_info;
        error_info = NULL;
    }
}
uint64_t getTickCountMs()
{
    struct timespec ts;

    clock_gettime(CLOCK_MONOTONIC, &ts);

    return (uint64_t)(ts.tv_nsec / 1000000) + ((uint64_t)ts.tv_sec * 1000ull);
}


template <typename Base, typename Derived>
static constexpr bool instanceOf() {
    return std::is_base_of<Base, Derived>();
}

std::string getPath()
{
    char* tmp = getcwd(NULL, 0);
    std::string path(tmp);
    std::string substring = "ComputerVision";
    int idx = path.find(substring);
    free(tmp);
    return (path.substr(0, idx) + substring +"/");
    // path = path.substr(0, idx) + substring + "/resource/Videos/";
}

std::string getConfigPath()
{
    return getPath() + "config/";
}

string replace(const string& old_value, const string& new_value, const string& str)
{
    string ret = str;
    replaceSrc(old_value, new_value, ret);
    return ret;
}

inline void replaceSrc(const string& old_value, const string& new_value, string& str)
{
    while(true)   {   
    string::size_type   pos(0);   
    if(   (pos=str.find(old_value))!=string::npos   )   
        str.replace(pos,old_value.length(),new_value);   
        else   break;   
    }
}